<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item
        ><a href="/admin" @click="resetDefaultActivePath"
          >首页</a
        ></el-breadcrumb-item
      >
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容卡片区域 -->
    <el-card>
      <el-form :model="searchData" class="demo-form-inline">
        <el-form-item label="" style="width: 100%">
          <el-input
            v-model="searchData.key"
            placeholder="请输入关键字"
          ></el-input>
        </el-form-item>
        <el-form-item label="" style="width: 100%">
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item label="" style="width: 100%">
          <el-button type="primary" @click="addRole">添加</el-button>
        </el-form-item>
      </el-form>
      <!-- 中间表格区域 -->
      <el-table :data="tableData" style="width: 100%" :border="true">
        <el-table-column label="">
          <template #default="{ $index }">
            {{
              (searchData.currentPage - 1) * searchData.pageSize + $index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-switch
              v-model="row.roleState"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeState(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="showEditRoleDialog(row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="destroyRole(row.id)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="showRightsDialog(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--底部分页区域-->
    <el-pagination
      style="text-align: center; padding-top: 20px"
      :current-page="searchData.currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchData.pageSize"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>

    <!--添加角色对话框-->
    <el-dialog
      :title="roleData.id ? '编辑角色' : '添加角色'"
      :visible.sync="addRoleDialogVisible"
      width="30%"
      @close="close"
    >
      <el-form
        ref="form"
        :model="roleData"
        :rules="addRoleRules"
        label-width="0px"
      >
        <el-form-item label="" prop="roleName">
          <el-input
            v-model="roleData.roleName"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item label="" prop="roleDesc">
          <el-input
            v-model="roleData.roleDesc"
            prefix-icon="el-icon-info"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="createRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加权限对话框 -->
    <el-dialog title="添加权限" :visible.sync="RightsDialogVisible" width="30%">
      <el-tree
        :data="treeData"
        :props="defaultProps"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="defaultCheckedKeys"
        ref="tree"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sumbitRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  getRoles,
  getAddRoles,
  delRole,
  updateRoles,
  getOneRoleInfo,
  getAllRights,
  createRoleRights,
  delRoleRights,
} from "@/api/index";
import { ElForm } from "element-ui/types/form";
import { ElTree } from "element-ui/types/tree";
import { Component, Ref, Vue } from "vue-property-decorator";
interface SearchData {
  key: string;
  currentPage: number;
  pageSize: number;
}
interface RoleData {
  id: string;
  roleName: string;
  roleDesc: string;
  roleState: boolean;
}
@Component({
  name: "Roles",
  components: {},
})
export default class Roles extends Vue {
  private resetDefaultActivePath() {
    sessionStorage.removeItem("activePath");
  }
  private addRoleDialogVisible = false; // 角色对话框
  private RightsDialogVisible = false; // 权限对话框
  private treeData: any = [
    // 树形数据
    {
      label: "一级 1",
      children: [
        {
          label: "二级 1-1",
          children: [
            {
              label: "三级 1-1-1",
            },
          ],
        },
      ],
    },
  ];
  private defaultProps = {
    // 树形的属性
    children: "children",
    label: "rightsName",
  };
  // 搜索的数据
  private searchData = {
    key: "", // 关键字
    currentPage: 1, // 当前页
    pageSize: 5, // 页容量
  } as SearchData;
  private totalCount: number = 0;
  // 新增和编辑的数据
  private roleData = {
    id: "",
    roleName: "",
    roleDesc: "",
    roleState: true,
  } as RoleData;
  private addRoleRules = {
    roleName: [
      { required: true, message: "请输入角色名称", trigger: "blur" },
      { min: 2, message: "长度至少2个字符", trigger: "blur" },
    ],
    roleDesc: [
      { required: true, message: "请输入角色描述", trigger: "blur" },
      { min: 1, message: "长度至少1个字符", trigger: "blur" },
    ],
  };
  private tableData: any = [
    // { roleName: "超级管理员", roleDesc: "管理者", roleState: true },
    // { roleName: "员工", roleDesc: "啥都干", roleState: false },
    // { roleName: "财务", roleDesc: "管钱", roleState: true },
    // { roleName: "人力", roleDesc: "管人", roleState: true },
  ];
  private async created() {
    this.getRoles();
  }
  // 获取所有角色(带查询条件)
  private async getRoles() {
    const result: any = await getRoles(this.searchData);
    // console.log(result);
    this.tableData = result.data.data.roles;
    this.totalCount = result.data.data.count;
  }
  // 分配权限
  private defaultCheckedKeys:any[] = []; // 指定默认选中的权限
  private currentRoleId = ""; // 当前点击分配权限的那个角色id
  @Ref() readonly tree!: ElTree<any, any>;
  private async showRightsDialog(row:any) {
    this.RightsDialogVisible = true;
    let result: any = await getAllRights();
    // console.log(result);
    this.treeData = this.listParts(result.data.data, 0);
    // console.log(this.treeData);
    this.currentRoleId = row.id;
    // 显示默认选中的权限
    this.defaultCheckedKeys = row.rights.map((item:any) => {
     if(item.level === 2){ // 三级的权限
        return item.id
     }
    })
    // console.log(this.defaultCheckedKeys);
    this.tree ? this.tree.setCheckedKeys(this.defaultCheckedKeys) : '' // 设置这一次的默认权限
  }
  // 递归找出父级部门的所属子部门
  private listParts(list: Array<[]>, tolpid: any) {
    const arr: any[] = [];
    list.forEach((item: any) => {
      if (item.pid === tolpid) {
        item.children = this.listParts(list, item.id);
        arr.push(item);
      }
    });
    return arr;
  }
  // 分配权限确定按钮
  private sumbitRights() {
    this.RightsDialogVisible = false;
    // 1.获取当前所有选中和半选中的权限
    const CheckedKeys:any[] = [
      ...this.tree.getCheckedKeys(),
      ...this.tree.getHalfCheckedKeys(),
    ];
    // console.log(CheckedKeys,'1111111');
    // 2.获取新增的权限
    // const addCheckedKeys = CheckedKeys.filter((id) => {
    //   return !this.defaultCheckedKeys.includes(id);
    // });
    // 3.获取操作后以前剩余的权限
    // const oldCheckedKeys = CheckedKeys.filter((id) => {
    //   return this.defaultCheckedKeys.includes(id);
    // });
    // 4.获取删除的权限
    // const removeCheckedKeys = this.defaultCheckedKeys.filter((id) => {
    //   return !oldCheckedKeys.includes(id);
    // });
    // console.log('这是原来的权限',this.defaultCheckedKeys);
    // console.log('这是新增的权限',addCheckedKeys);
    // console.log('这是剩余的权限',oldCheckedKeys);
    // console.log('这是删除的权限',removeCheckedKeys);

    // 新增权限
    createRoleRights({
        roleId: this.currentRoleId,
        rightsIds: CheckedKeys,
      })
        .then((response: any) => {
          if (response.status === 200) {
            this.getRoles();
            (this as any).$message.success("添加权限成功");
          } else {
            (this as any).$message.error(response.data.msg);
          }
        })
        .catch((error) => {
          (this as any).$message.error(error.response.data.msg);
        });
    // if (addCheckedKeys.length > 0) {
    //   createRoleRights({
    //     roleId: this.currentRoleId,
    //     rightsIds: addCheckedKeys,
    //   })
    //     .then((response: any) => {
    //       if (response.status === 200) {
    //         this.getRoles();
    //         (this as any).$message.success("添加权限成功");
    //       } else {
    //         (this as any).$message.error(response.data.msg);
    //       }
    //     })
    //     .catch((error) => {
    //       (this as any).$message.error(error.response.data.msg);
    //     });
    // }
    // 移除权限
    // if(removeCheckedKeys.length > 0){
    //   delRoleRights(this.currentRoleId,{rightsIds:removeCheckedKeys})
    //   .then((response: any) => {
    //       if (response.status === 200) {
    //         this.getRoles();
    //         (this as any).$message.success("删除权限成功");
    //       } else {
    //         (this as any).$message.error(response.data.msg);
    //       }
    //     })
    //     .catch((error) => {
    //       (this as any).$message.error(error.response.data.msg);
    //     });
    // }
  }
  // 查询
  private search() {
    this.getRoles();
  }
  // 新增
  @Ref() readonly form!: ElForm;
  private addRole() {
    this.addRoleDialogVisible = true;
    // 让弹窗出来后在去重置 使用@$nextTick
    this.$nextTick(() => {
      // 重置表单
      this.form.resetFields();
    });
  }
  // 编辑
  private async showEditRoleDialog(id: string) {
    this.addRoleDialogVisible = true;
    const result: any = await getOneRoleInfo(id);
    // console.log(result);
    // this.$nextTick(()=>{
    this.roleData = result.data.data;
    // })
  }
  // 新增角色或编辑角色的确定按钮
  private createRole() {
    this.addRoleDialogVisible = false;
    this.form.validate((valid) => {
      if (valid) {
        if (!this.roleData.id) {
          // 没有id则是新增角色
          getAddRoles(this.roleData)
            .then((response: any) => {
              console.log(response);
              const role = response.data.data;
              // 追加到列表最后
              // this.tableData.push(role);
              this.getRoles();
              (this as any).$message.success("添加角色成功");
            })
            .catch((e) => {
              (this as any).$message.error(e.response.data.msg);
            });
        } else {
          // 编辑角色
          updateRoles(this.roleData.id, this.roleData)
            .then((response: any) => {
              console.log(response);
              this.getRoles();
              (this as any).$message.success("更新角色成功");
            })
            .catch((e) => {
              (this as any).$message.error(e.response.data.msg);
            });
        }
      } else {
        (this as any).$message.error("数据格式不对");
      }
    });
  }
  // 状态按钮改变
  private changeState(row: any) {
    // console.log(row);
    updateRoles(row.id, row)
      .then((result: any) => {
        if (result.status === 200) {
          this.getRoles();
          (this as any).$message.success("更新角色状态成功");
        } else {
          row.roleState = !row
            .roleState(this as any)
            .$message.error("更新角色状态失败");
        }
      })
      .catch((e) => {
        row.roleState = !row
          .roleState(this as any)
          .$message.error("更新角色状态失败");
      });
  }
  // 删除
  private destroyRole(id: string) {
    (this as any)
      .$confirm("确定删除该角色吗?", "提示", {
        // confirmButtonText: "确定",
        // cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        delRole(id)
          .then((response: any) => {
            // // 当前页如果剩下一条数据且页码大于1 则让页码减1
            if (
              this.tableData.length === 1 &&
              this.searchData.currentPage > 1
            ) {
              this.searchData.currentPage--;
            }
            // 刷新用户列表
            this.getRoles();
            (this as any).$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch((e: any) => {
            (this as any).$message.error(e.response.data.msg);
          });
      })
      .catch(() => {
        (this as any).$message({
          type: "info",
          message: "已取消删除",
        });
      });
  }

  // 分页相关操作
  private handleCurrentChange(current: any) {
    // console.log(current);
    this.searchData.currentPage = current;
    this.getRoles();
  }
  private handleSizeChange(size: any) {
    // console.log(size);
    this.searchData.pageSize = size;
    this.getRoles();
  }

  // 关闭弹窗
  private close() {
    this.roleData = {
      id: "",
      roleName: "",
      roleDesc: "",
      roleState: true,
    };
    this.addRoleDialogVisible = false;
    // 重置
    this.form.resetFields();
  }
}
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  padding-bottom: 20px;
}
.demo-form-inline {
  display: flex;
  justify-content: center;
}
.query_role {
  padding: 0 20px;
}
.el-pagination {
  padding-top: 20px;
}
.el-button {
  margin-left: 15px;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
